/*
    BibleNotebook - A bible reader software
    Copyright (C) 2014  Williams Fernando Lopez

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
 */

/*
 * ReaderPanel.java
 *
 * Created on 2/07/2013, 02:55:37 PM
 */

package com.simplebible.ui.components;

import wl.ui.ButtonLabel;
import wl.ui.CanvasSlide;
import java.awt.event.AdjustmentEvent;
import java.awt.Color;
import java.awt.Component;
import java.awt.MouseInfo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentListener;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.event.HyperlinkEvent;
import com.simplebible.bible.objects.Book;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.HyperlinkListener;
import com.simplebible.bible.BibleReader;
import com.simplebible.bible.BibleUtils;
import wl.util.TextResourcesUtil;
import wl.util.Utils;
import com.simplebible.dictionary.DictionaryUtils;
import com.simplebible.bible.objects.Abreviation;
import com.simplebible.bible.objects.Bible;
import com.simplebible.bible.objects.BookMark;
import com.simplebible.bible.objects.Chapter;
import com.simplebible.bible.objects.Note;
import com.simplebible.objects.Preferences;
import com.simplebible.bible.objects.Referencia;
import com.simplebible.bible.objects.SearchResult;
import wl.util.TextPosition;
import com.simplebible.bible.objects.Title;
import com.simplebible.bible.objects.Verse;
import wl.ui.SearchPanel;

/**
 *
 * @author Williams Lopez
 */
public class ReaderPanel extends javax.swing.JPanel {

    
    private Selector selector = new Selector();
    private ConfigPanel configPanel = new ConfigPanel();
    private Bible bible = null;
    private Book currentBook;
    private Chapter currentChapter;
    private Verse currentVerse;

    private List<SearchResult> lastSearchResult;
    private String             lastSearchText;

    private ReaderPanel dualPanel  = null;
    private boolean dualPanelIndicator = false;
    
    private VerseQuickOptionPane verseOptions = null;

    boolean animationEnable = true;

    private SearchPanel searchPanel;



    /** Creates new form ReaderPanel */
    public ReaderPanel() {
        initComponents();

        this.labelLastSearchResult.setVisible(false);
        this.textPane.addHyperlinkListener(new HyperlinkListener() {
            public void hyperlinkUpdate(HyperlinkEvent e) {


                try {
                    String url = e.getDescription();
                    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                        if (url.startsWith("search:")) {
                            url = url.replace("search:", "");
                            Abreviation abrv = Abreviation.parse(url);
                            setCapitulo(abrv);
                        } else if (url.startsWith("verse:")) {
                            url = url.replace("verse:", "");
                            if (verseOptions != null) {
                                Abreviation abrv = Abreviation.parse(url + "." + bible.getAbreviation().getBible());
                                int x = (int) (MouseInfo.getPointerInfo().getLocation().getX() - textPane.getLocationOnScreen().getX());
                                int y = (int) (MouseInfo.getPointerInfo().getLocation().getY() - textPane.getLocationOnScreen().getY());
                                verseOptions.show(abrv, textPane, x, y);
                            }
                        } else if (url.startsWith("referencia:")) {
                            url = url.replace("referencia:", "");
                            Abreviation abrv = Abreviation.parse(url);
                            setCapitulo(abrv);
                        } else if(url.startsWith("verseword:")){
                            url = url.replace("verseword:", "");
                            String[] datos = url.split("[?][?]");
                            String str_abrv = datos[0];
                            String str_word = datos[1];
                            if (verseOptions != null) {
                                Abreviation abrv = Abreviation.parse(str_abrv + "." + bible.getAbreviation().getBible());
                                int x = (int) (MouseInfo.getPointerInfo().getLocation().getX() - textPane.getLocationOnScreen().getX());
                                int y = (int) (MouseInfo.getPointerInfo().getLocation().getY() - textPane.getLocationOnScreen().getY());
                                verseOptions.show(abrv,str_word, textPane, x, y);
                            }
                        }else if(url.startsWith("nota:")){
                            url =url.replace("nota:", "");
                            MainPanel.showNotification(url, null);
                        }
                    } else if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
                        if (url.startsWith("referencia:")) {
                            try {
                                url = url.replace("referencia:", "");
                                Abreviation abrv = Abreviation.parse(url);
                                Verse v = BibleUtils.findVerse(bible, abrv);
                                if (v != null) {
                                    MainPanel.showNotification("<b>" + BibleUtils.getHumanName(bible, v.getAbreviation()) + "</b><br/>" + v.getTextWithoutMarks(), null);
                                }
                            } catch (Exception ex) {
                                Utils.printToLog("Error al obtener el texto de la referencia", ex, Preferences.LOG_LEVEL_ERROR);
                            }
                        }

                    } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
                        if (url.startsWith("referencia:")) {
                            MainPanel.hideNotification();
                        }
                    }

                } catch (Exception exc) {
                    Utils.printToLog("Error", exc, Preferences.LOG_LEVEL_ERROR);
                    MainPanel.showNotification("generic_error", exc);
                }

            }


        });

        selector.setSelectListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    setCapitulo((Abreviation) e.getSource());
                } catch (Exception exc) {
                    Utils.printToLog("Error", exc, Preferences.LOG_LEVEL_ERROR);
                    MainPanel.showNotification("generic_error", exc);
                }
            }
        });

        selector.setSearchEndListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource()!=null && (e.getSource() instanceof List)){
                    List<SearchResult> list = (List<SearchResult>)e.getSource();
                    setSearchResult((List<SearchResult>)e.getSource(), e.getActionCommand());
                }
            }
        });


        configPanel.setMarcadoresControlListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() != null && (e.getSource() instanceof Boolean)){
                    Preferences.getInst().setMarcadoresEnables((Boolean)e.getSource());
                    refresh();
                }
            }
        });

        configPanel.setReferenciasControlListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() != null && (e.getSource() instanceof Boolean)){
                    Preferences.getInst().setReferenciasEnabled((Boolean)e.getSource());
                    refresh();
                }
            }
        });

        configPanel.setBackgroundColorControlListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() != null && (e.getSource() instanceof Color)){
                    setBackgroundColor((Color)e.getSource());
                    Preferences.getInst().setBackgrounColor((Color)e.getSource());
                    refresh();
                }
            }
        });

        configPanel.setFontColorControlListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() != null && (e.getSource() instanceof Color)){
                    Preferences.getInst().setForegroundColor((Color)e.getSource());
                    refresh();
                }
            }
        });

        configPanel.setFontSizeControlListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() != null && e.getSource() instanceof Integer){
                    Preferences.getInst().setFontSize((Integer)e.getSource());
                    refresh();
                }
            }
        });

        configPanel.setSelectVersionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource()!=null && (e.getSource() instanceof Bible)){
                    bible = (Bible)e.getSource();

                    if(currentBook != null){
                        currentBook = BibleUtils.findBook(bible, currentBook.getAbreviation().getBook());   
                    }

                    if(currentBook == null){
                            currentBook = bible.getBooks().get(0);
                    }

                    if(currentChapter != null){
                        currentChapter = BibleUtils.findChapter(currentBook, currentChapter.getAbreviation().getChapter());
                    }

                    if(currentChapter == null){
                        currentChapter = currentBook.getChapters().get(0);
                    }

                    currentVerse = currentChapter.getVerses().get(0);
                    refresh();
                }
            }
        });

        configPanel.setDiccionarioControlListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() != null && (e.getSource() instanceof Boolean)){
                    Preferences.getInst().setDictionaryEnabled((Boolean)e.getSource());
                    refresh();
                }
            }
        });


        goToPreferences();


        try{
            TextResourcesUtil.registrarComponente(this);
        }catch(Exception e){
            Utils.printToLog("Error al setear los textos. ", e,Preferences.LOG_LEVEL_ERROR);
        }


        this.jScrollPane1.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent e) {
                if(dualPanel!=null){
                    int max = dualPanel.jScrollPane1.getVerticalScrollBar().getMaximum();
                    int min = dualPanel.jScrollPane1.getVerticalScrollBar().getMinimum();
                    if(e.getValue() >= min && e.getValue() <= max){
                        dualPanel.jScrollPane1.getVerticalScrollBar().setValue(e.getValue());
                    }
                }
            }
        });

        setBackgroundColor(Preferences.getInst().getBackgrounColor());
        this.jScrollPane1.setDoubleBuffered(true);
        this.jScrollPane1.getVerticalScrollBar().setDoubleBuffered(true);
        searchPanel = new SearchPanel();
        searchPanel.setTextComponent(textPane, jScrollPane1);
        searchPanel.setOpaque(false);
    }


    public void setBackgroundColor(Color color){
        jPanel1.setBackground(color);
        jScrollPane1.setBackground(color);
        textPane.setBackground(color);
    }

    public final void goToPreferences()  {
        try {
            String b = Preferences.getInst().getLastVersion();
            String l = Preferences.getInst().getLastBook();
            String c = Preferences.getInst().getLastChapter();
            String v = Preferences.getInst().getLastVerse();

            Abreviation abrv = new Abreviation();
            abrv.setBible(b);
            abrv.setBook(l);
            abrv.setChapter(c);
            abrv.setVerse(v);

            setCapitulo(abrv);
            setAnimationEnable(Preferences.getInst().isAnimation());
            return;
        } catch (Exception e) {
            Utils.printToLog("Error al ir a las preferencias", e, Preferences.LOG_LEVEL_ERROR);
        }

        try {
            List<Bible> lb = BibleReader.getVersions();
            if (!lb.isEmpty()) {
                Abreviation abrv = lb.get(0).getBooks().get(0).getChapters().get(0).getVerses().get(0).getAbreviation();
                abrv = abrv.cloneChanging(Abreviation.FIELD_BIBLE, lb.get(0).getAbreviation().getBible());
                setCapitulo(abrv);
            }
        } catch (Exception ex) {
            Utils.printToLog("Error al mostrar el capitulo", ex, Preferences.LOG_LEVEL_ERROR);
        }
    }

    private void refresh(){
        try{
            setCapitulo(this.currentBook,this.currentChapter,this.currentVerse,0);
        }catch(Exception e){
            MainPanel.showNotification("generic_error", e);
            Utils.printToLog("Error al refrescar el capitulo", e, Preferences.LOG_LEVEL_ERROR);
        }
    }

    public void refreshAll() {
        try {
            if (this.currentChapter != null) {
                try {
                    setCapitulo(this.currentChapter.getAbreviation());
                } catch (Exception e) {
                    Utils.printToLog("Error al ir al capitulo", e, Preferences.LOG_LEVEL_ERROR);
                    goToPreferences();
                }
            } else {
                goToPreferences();
            }

            configPanel.refresh();


        } catch (Exception e) {
            Utils.printToLog("Error al refrescar", e, Preferences.LOG_LEVEL_ERROR);
            MainPanel.showNotification("generic_error", e);
        }
    }

    public void setSearchResult(List<SearchResult> result, String searchedText) {

        this.labelLastSearchResult.setVisible(true);
        this.lastSearchResult = result;
        this.lastSearchText = searchedText;

        StringBuilder sbCap = new StringBuilder();

        String fontcolor = Utils.colorToHex(Preferences.getInst().getForegroundColor());
        String background = Utils.colorToHex(Preferences.getInst().getBackgrounColor());
        String fontsize = Preferences.getInst().getFontSize() + "";
        String fontFamily = Preferences.getInst().getFont();

        sbCap.append("<div style='background-color:");
        sbCap.append(background);
        sbCap.append(";font-size:");
        sbCap.append(fontsize);
        sbCap.append("px;font-family:");
        sbCap.append(fontFamily);
        sbCap.append(";color:");
        sbCap.append(fontcolor);
        sbCap.append(";'>");

        if (result == null || result.isEmpty()) {
            sbCap.append("<p><b>No se encontr&oacute; ninguna coincidencia</b></p>");
        } else {

            if (result.size() >= BibleUtils.SEARCH_LIMIT) {
                sbCap.append("<h2>Se encontraron más de "+BibleUtils.SEARCH_LIMIT+" resultados</h2>");
                sbCap.append("<h3><font color=red>Se muestran únicamente los primeros "+BibleUtils.SEARCH_LIMIT+"</font></h2");
            } else {
                sbCap.append("<h2>Resultados encontrados: ");
                sbCap.append(result.size());
                sbCap.append("</h2");
            }

            int resultNum = 0;
            for(SearchResult sr: result){
                resultNum++;
                Verse v = sr.getVerse();
                List<TextPosition> r = sr.getResults();

                StringBuilder sb = new StringBuilder();

                sb.append("<p>");
                sb.append("<b>");
                sb.append(resultNum);
                sb.append(") ");
                sb.append(BibleUtils.getHumanName(bible, v.getAbreviation()));
                sb.append("</b><br/>");
                sb.append("<a href='search:");
                sb.append(v.getAbreviation());
                sb.append("' style='text-decoration:false;color:");
                sb.append(fontcolor);
                sb.append("'>");

                HashMap<String,String> keys = new HashMap<String, String>();
                StringBuilder sbtmp = new StringBuilder(v.getTextWithoutMarks());
                int keyindex = 1;

                for (TextPosition tp : r) {
                    String text = v.getTextWithoutMarks().substring(tp.getStart(), tp.getEnd());
                    String key = Integer.toString(keyindex);
                    while(key.length()< text.length()){ key = "#" + key;}
                    sbtmp.replace(tp.getStart(), tp.getEnd(), key);
                    keys.put(key, "<font color='red' style='color:red'><b>"+ text + "</b></font>");
                    keyindex++;
                }

                Iterator<String> itKey = keys.keySet().iterator();
                String str = sbtmp.toString();
                while(itKey.hasNext()){
                    String k = itKey.next();
                    str = str.replace(k,keys.get(k));
                }
                sb.append(str);
                sb.append("</a>");
                sb.append("</p>");

                sbCap.append(sb);
                
            }
        }
        sbCap.append("</div>");
        
        System.out.println(sbCap.toString());


        this.textPane.setText(sbCap.toString());
        this.labelSelector.setText(searchedText);
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                jScrollPane1.getVerticalScrollBar().setValue(0);
            }
        });



    }

    public void setCapitulo(Abreviation a) throws Exception{
        setCapitulo(a,0);
    }



    public void setCapitulo(Abreviation a, int animationType) throws Exception{
            if(a.getBible()!= null && !a.getBible().trim().equals("")){
                this.bible = BibleReader.getBible(a.getBible());
            }else{
                if(this.bible == null){
                    return;
                }
            }
            
            this.currentBook = BibleUtils.findBook(bible, a.getBook());
            this.currentChapter = BibleUtils.findChapter(this.currentBook, a.getChapter());
            if(a.getVerse() !=null){
                this.currentVerse = null;
                this.currentVerse = BibleUtils.findVerse(this.currentChapter,a.getVerse());
            }
            setCapitulo(currentBook,currentChapter,currentVerse,animationType);
    }


    public void setCapitulo(Book book, Chapter cap, Verse ver,int animationType) throws Exception{

        if(bible == null){
            JOptionPane.showMessageDialog(this, "No se ha seleccionado una biblia");
        }

        String fontcolor   = Utils.colorToHex(Preferences.getInst().getForegroundColor());
        String background  = Utils.colorToHex(Preferences.getInst().getBackgrounColor());
        String fontsize    = Preferences.getInst().getFontSize()+"";
        String fontFamily  = Preferences.getInst().getFont();


        List<Verse> versiculos = cap.getVerses();
        StringBuilder sbCap = new StringBuilder();
        List<BookMark> list = BibleReader.getBookMarks(cap);

        if(Preferences.getInst().isDictionaryEnabled()){
            sbCap.append("<div align='left' style='background-color:");
        }else{
            sbCap.append("<div align='justify' style='background-color:");
        }
        //sbCap.append(background);
        sbCap.append("none");
        sbCap.append(";font-size:");
        sbCap.append(fontsize);
        sbCap.append("px;font-family:");
        sbCap.append(fontFamily);
        sbCap.append(";color:");
        sbCap.append(fontcolor);
        sbCap.append(";'>");
        sbCap.append("<h2>");
        sbCap.append(book.getHumanName() + " " + cap.getHumanName());
        sbCap.append("</h2>");

        int ordenTitulo = 0;

        for(Verse v : versiculos){


            StringBuilder sb = new StringBuilder();
            

            //Verificando si hay titulo antes de este versiculo
            if (cap.getTitles() != null) {
                for (Title t : cap.getTitles()) {
                    if(t.getPosition().equals(Integer.toString(ordenTitulo))){
                        sb.append("<h3>");
                        sb.append(t.getHumanName());
                        sb.append("</h3>");
                    }
                }
            }

            

            if(ver!= null && v.equals(ver)){
                sb.append("<p style='background-color:#FEFECC;margin-top: 0'>\n");
            }else{
                sb.append("<p style='margin-top: 0;'>\n");
            }

            String ahref = "<a>";


            if(!Preferences.getInst().isDictionaryEnabled()){
                ahref = "<a href='verse:"+v.getAbreviation()+"' style='text-decoration:none;color:"+fontcolor+"'>";
                sb.append(ahref);
                sb.append("<sup>");
                sb.append(v.getHumanName());
                sb.append("</sup>");
                sb.append("&nbsp;");
                sb.append(v.getText());
                sb.append("</a>\n");
            }else{
                ahref = "<a href='verseword:"+v.getAbreviation()+"??{w}' style='text-decoration:none;color:"+fontcolor+"'>";
                sb.append("<sup>");
                sb.append(v.getHumanName());
                sb.append("</sup>");
                sb.append("&nbsp;");
                sb.append(DictionaryUtils.addHrefToWords(v.getText(), ahref));
            }

            sb.append("<endverse/>");

            //Mostrar marcadores
            if(Preferences.getInst().isMarcadoresEnables()){
                if(list!=null && !list.isEmpty()){
                    StringBuilder bmSB = new StringBuilder();
                    for(BookMark bm : list){
                        if (bm.getAbreviation().equals(v.getAbreviation())) {
                            String bmfontcolor;
                            if (bm.getColor() != null) {
                                bmfontcolor = Utils.colorToHex(bm.getColor());
                            } else {
                                bmfontcolor = fontcolor;
                            }
                            bmSB.append("<br/><span style='color:");
                            bmSB.append(bmfontcolor);
                            bmSB.append(";font-size:");
                            bmSB.append((Preferences.getInst().getFontSize() - 3));
                            bmSB.append("px'>");
                            bmSB.append("<b>");
                            bmSB.append(bm.getPalabrasClave());
                            bmSB.append("</b>");
                            bmSB.append(" ");
                            bmSB.append(bm.getComentario());
                            bmSB.append("</span>");
                        }
                    }
                    sb.append(bmSB);
                }
            }

            sb.append("</p>");



            //first because notes start with ## and references with #
            if (v.getNotes() != null && !v.getNotes().isEmpty()) {
                for (Note r : v.getNotes()) {
                    StringBuilder sbref = new StringBuilder();
                    if (Preferences.getInst().isReferenciasEnabled()) {
                        try {
                            sbref.append("</a> <a href='nota:");
                            sbref.append(r.getText());
                            sbref.append("' style='text-decoration:false;color:");
                            sbref.append("red");
                            sbref.append(";font-size:10px'><sub>");
                            sbref.append(r.getHumanName());
                            sbref.append("</sub></a> ");
                            sbref.append(ahref);
                        } catch (Exception e) {
                            Utils.printToLog("Error", e, Preferences.LOG_LEVEL_ERROR);
                        }
                    }
                    int inicio = sb.indexOf(r.getPosicion());
                    int fin = inicio + r.getPosicion().length();

                    if(inicio >=0 && fin >=0){
                        sb.replace(inicio, fin, sbref.toString());
                    }else if(inicio < 0){
                        inicio = sb.indexOf("<endverse/>");
                        if(inicio >=0){
                            sb.insert(inicio, sbref.toString());
                        }
                    }

                }
            }

        
            if (v.getRefCruzadas() != null && !v.getRefCruzadas().isEmpty()) {
                for (Referencia r : v.getRefCruzadas()) {
                    StringBuilder sbref = new StringBuilder();
                    if (Preferences.getInst().isReferenciasEnabled()) {
                        for (Abreviation ra : r.getReferencias()) {
                            try{
                                sbref.append("</a> <a href='referencia:");
                                sbref.append(ra.toString());
                                sbref.append("' style='text-decoration:false;color:");
                                sbref.append(Utils.colorToHex(Preferences.getInst().getForegroundColor()));
                                sbref.append(";font-size:10px'><sub>");
                                sbref.append(BibleUtils.getHumanName(bible, ra,4));
                                sbref.append("</sub></a> ");
                                sbref.append(ahref);
                            }catch(Exception e){
                                Utils.printToLog("Error", e, Preferences.LOG_LEVEL_ERROR);
                                sbref.append(ra.toString());
                            }
                        }
                    }
                    int inicio = sb.indexOf(r.getPosicion());
                    int fin = inicio + r.getPosicion().length();

                    if(inicio >=0 && fin >=0){
                        sb.replace(inicio, fin, sbref.toString());
                    }else if(inicio < 0){
                        inicio = sb.indexOf("<endverse/>");
                        if(inicio >=0){
                            sb.insert(inicio, sbref.toString());
                        }
                    }

                }
            }


            

            sbCap.append(sb);
            ordenTitulo++;
        }
        sbCap.append("</div>");

        sbCap.append("<div><font color='gray' size='3'>");
        if(bible.getCopyRight()!=null){
            sbCap.append("<p>");
            sbCap.append(bible.getCopyRight());
            sbCap.append("</p>");
        }
        if(bible.getCopyRightContactName()!=null){
            sbCap.append("<p>");
            sbCap.append(bible.getCopyRightContactName());
            sbCap.append("</p>");
        }
        if(bible.getCopyRightContactAdrs()!=null){
            sbCap.append("<p>");
            sbCap.append(bible.getCopyRightContactAdrs());
            sbCap.append("</p>");
        }
        if(bible.getCopyRightContactNote()!=null){
            sbCap.append("<p>");
            sbCap.append(bible.getCopyRightContactNote());
            sbCap.append("</p>");
        }
        sbCap.append("</font></div>");

        if(animationEnable && animationType > 0){
            this.textPane.setAnimationSeparatorColor(Preferences.getInst().getBackgrounColor());
            this.textPane.setTextWithAnimation(sbCap.toString(),animationType);
        }else{
            this.textPane.setText(sbCap.toString());
        }
        this.labelSelector.setText(book.getHumanName()+" "+cap.getHumanName());
        this.labelNextChapter.setEnabled(true);
        this.labelPreviousChapter.setEnabled(true);

        final Verse fver = ver;

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                if(fver!=null){
                    //Ubicamos el scroll donde se encuentra el versiculo
                    try{


                        String text = textPane.getDocument().getText(0, textPane.getDocument().getLength());
                        String versetext = fver.getText();
                        if(versetext.indexOf("#")>=0){
                            versetext = versetext.substring(0, versetext.indexOf("#"));
                        }

                        int pos = text.indexOf(versetext);

                        if(pos>=0){
                            textPane.setCaretPosition(pos);
                        }
                    }catch(Exception ex){
                        Utils.printToLog("Error", ex, Preferences.LOG_LEVEL_ERROR);
                        jScrollPane1.getVerticalScrollBar().setValue(0);
                    }
                }else{
                    jScrollPane1.getVerticalScrollBar().setValue(0);
                }
            }
        });
        labelVersion.setText(bible.getAbreviation().getBible().toUpperCase());

        if(dualPanel!=null){
            dualPanel.setCapitulo(cap.getAbreviation().cloneChanging(Abreviation.FIELD_BIBLE, null),animationType);
        }

        if(!dualPanelIndicator){
            Preferences.getInst().setLastVersion(bible.getAbreviation().getBible());
            Preferences.getInst().setLastBook(book.getAbreviation().getBook());
            Preferences.getInst().setLastChapter(cap.getAbreviation().getChapter());
        }
        
        this.labelVersion.setText(this.bible.getAbreviation().getBible().toUpperCase());

    }


    public void showConfigPanel(){
        showConfigPanel(this.labelVersion);
    }

    public void showSelector(){
        showSelector(this.labelSelector);
    }

    private void showConfigPanel(Component inv){
        configPanel.show(inv,0,this.labelVersion.getHeight());;
    }

    private void showSelector(Component inv){
        selector.setBible(bible);
        selector.setSelected(currentBook, currentChapter);
        selector.show(inv,0,this.labelSelector.getHeight());
    }

    public void nextChapter(){
        try {
            int nexcap = this.currentBook.getChapters().indexOf(this.currentChapter);
            int nexbok = this.bible.getBooks().indexOf(this.currentBook);

            if(nexcap < this.currentBook.getChapters().size()-1){
                nexcap++;
            }else{
                nexcap = 0;
                if(nexbok < this.bible.getBooks().size()-1){
                    nexbok++;
                }else{
                    nexbok=0;
                }
            }

            this.currentBook = this.bible.getBooks().get(nexbok);
            this.currentChapter = this.currentBook.getChapters().get(nexcap);

            setCapitulo(currentBook, currentChapter, null,CanvasSlide.HORIZONTAL_RIGHT_TO_LEFT);

        } catch (Exception e) {
            Utils.printToLog("Error al obtener el capitulo siguiente:"+e.getMessage(), e, Preferences.LOG_LEVEL_ERROR);
        }
    }


    public void previousChapter(){
        try {
            int nexcap = this.currentBook.getChapters().indexOf(this.currentChapter);
            int nexbok = this.bible.getBooks().indexOf(this.currentBook);

            if(nexcap > 0){
                nexcap--;
            }else{
                if(nexbok > 0){
                    nexbok--;
                }else{
                    nexbok=this.bible.getBooks().size()-1;
                }
                nexcap = this.bible.getBooks().get(nexbok).getChapters().size()-1;
            }

            this.currentBook = this.bible.getBooks().get(nexbok);
            this.currentChapter = this.currentBook.getChapters().get(nexcap);

            setCapitulo(currentBook, currentChapter, null,CanvasSlide.HORIZONTAL_LEFT_TO_RIGHT);

        } catch (Exception e) {
            Utils.printToLog("Error going to previous chapter", e, Preferences.LOG_LEVEL_ERROR);
            MainPanel.showNotification("previous_chapter_error", e);
        }
    }


    public void setDualPanel(ReaderPanel reader) {
        if (this == reader) {
            return;
        }

        if (reader == null) {
            if (dualPanel != null) {
                this.dualPanel.labelSelector.setVisible(true);
                if(lastSearchResult!=null){
                this.dualPanel.labelLastSearchResult.setVisible(true);
                }
                this.dualPanel.labelPreviousChapter.setVisible(true);
                this.dualPanel.labelNextChapter.setVisible(true);
            }
        } else {
            reader.dualPanelIndicator = true;
            reader.labelSelector.setVisible(false);
            reader.labelLastSearchResult.setVisible(false);
            reader.labelPreviousChapter.setVisible(false);
            reader.labelNextChapter.setVisible(false);
            
        }
        this.dualPanel = reader;
        this.refresh();

    }

    public void setVerseOptionPanel(VerseQuickOptionPane comp){
        this.verseOptions = comp;
    }

    public Bible getCurrentBible(){
        return bible;
    }

    public boolean isAnimationEnable() {
        return animationEnable;
    }

    public void setAnimationEnable(boolean animationEnable) {
        this.animationEnable = animationEnable;
    }

    

    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelSelector = new ButtonLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textPane = new wl.ui.AnimatedTextPane();
        labelNextChapter = new ButtonLabel();
        labelPreviousChapter = new ButtonLabel();
        labelVersion = new ButtonLabel();
        jLabel6 = new javax.swing.JLabel();
        labelLastSearchResult = new ButtonLabel();

        setBackground(new java.awt.Color(255, 255, 255));

        labelSelector.setFont(new java.awt.Font("Arial", 0, 14));
        labelSelector.setForeground(new java.awt.Color(153, 153, 153));
        labelSelector.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/1372829462_select.png"))); // NOI18N
        labelSelector.setText("Génesis 1:1");
        labelSelector.setToolTipText("Seleccionar capítulo");
        labelSelector.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        labelSelector.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelSelectorMouseClicked(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setForeground(new java.awt.Color(250, 250, 250));
        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.Y_AXIS));

        jScrollPane1.setBorder(null);

        textPane.setContentType("text/html");
        textPane.setEditable(false);
        jScrollPane1.setViewportView(textPane);

        jPanel1.add(jScrollPane1);

        labelNextChapter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/document_page_next.png"))); // NOI18N
        labelNextChapter.setToolTipText("Capítulo siguiente");
        labelNextChapter.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelNextChapterMouseClicked(evt);
            }
        });

        labelPreviousChapter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/document_page_previous.png"))); // NOI18N
        labelPreviousChapter.setToolTipText("Capítulo anterior");
        labelPreviousChapter.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelPreviousChapterMouseClicked(evt);
            }
        });

        labelVersion.setFont(new java.awt.Font("Arial", 1, 14));
        labelVersion.setForeground(new java.awt.Color(153, 153, 153));
        labelVersion.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        labelVersion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/bullet_arrow_down.png"))); // NOI18N
        labelVersion.setText("NVI");
        labelVersion.setToolTipText("Seleccionar versión, otras configuraciones");
        labelVersion.setInheritsPopupMenu(false);
        labelVersion.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelVersionMouseClicked(evt);
            }
        });

        jLabel6.setText("  ");

        labelLastSearchResult.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/1373006082_window_app_list_search.png"))); // NOI18N
        labelLastSearchResult.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                labelLastSearchResultActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(labelSelector, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelVersion, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelLastSearchResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelPreviousChapter)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelNextChapter)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(jLabel6))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelSelector)
                        .addComponent(labelVersion)
                        .addComponent(labelLastSearchResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(labelPreviousChapter)
                    .addComponent(labelNextChapter))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                .addGap(15, 15, 15))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void labelSelectorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelSelectorMouseClicked
        showSelector(evt.getComponent());
    }//GEN-LAST:event_labelSelectorMouseClicked

    private void labelVersionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelVersionMouseClicked
        showConfigPanel(evt.getComponent());
    }//GEN-LAST:event_labelVersionMouseClicked

    private void labelNextChapterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelNextChapterMouseClicked
        nextChapter();
    }//GEN-LAST:event_labelNextChapterMouseClicked

    private void labelPreviousChapterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelPreviousChapterMouseClicked
        previousChapter();
    }//GEN-LAST:event_labelPreviousChapterMouseClicked

    private void labelLastSearchResultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelLastSearchResultActionPerformed
        setSearchResult(lastSearchResult, lastSearchText);
    }//GEN-LAST:event_labelLastSearchResultActionPerformed


    


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private wl.ui.ButtonLabel labelLastSearchResult;
    private javax.swing.JLabel labelNextChapter;
    private javax.swing.JLabel labelPreviousChapter;
    private javax.swing.JLabel labelSelector;
    private javax.swing.JLabel labelVersion;
    private wl.ui.AnimatedTextPane textPane;
    // End of variables declaration//GEN-END:variables

}
